package club.kynb.mall.application.flow.user;

import club.kynb.mall.application.config.AuthConfig;
import club.kynb.mall.application.config.AuthProperties;
import club.kynb.mall.application.context.AuthenticationContext;
import club.kynb.mall.application.model.model.command.AuthenticationCommand;
import club.kynb.mall.application.model.model.dto.TokenDTO;
import club.kynb.mall.user.model.dto.UserDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.common.web.exception.Errors;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.UUID;

/**
 * @author kynb_club@163.com
 * @since 2020/12/18 1:48 下午
 * 构建token过滤器
 */
@Slf4j
@Component
@AllArgsConstructor
public class BuildTokenFilter implements Filter<AuthenticationContext> {
    private final AuthProperties authProperties;

    @Override
    public void doFilter(AuthenticationContext authenticationContext, FilterInvoker<AuthenticationContext> filterInvoker) {
        log.info("构建token过滤器 start");
        AuthenticationCommand authenticationCommand = authenticationContext.getAuthenticationCommand();
        Optional<AuthConfig> authConfig = authProperties.get(authenticationCommand.getClientType());
        AuthConfig config = authConfig.orElseThrow(() -> Errors.BIZ.exception("丢失对应客户端类型的认证配置"));
        UserDTO user = authenticationContext.getUser();
        TokenDTO token = authenticationContext.getToken();
        token.setTokenExpire(config.getTokenExpire());
        token.setIssue(System.currentTimeMillis());
        if (user.getPhone().equals("18058525327")) {
            token.setAccessToken("123456789");
        } else {
            token.setAccessToken(UUID.randomUUID().toString());
        }
        log.info("构建token过滤器 end");
        filterInvoker.invoke(authenticationContext);
    }
}
